package com.yizisu.basemvvm.utils

import android.content.Context
import android.content.SharedPreferences
import com.yizisu.basemvvm.gson

/**
 * 若红楼梦空，亦初心不变
 * 作者：thinker
 * 包名：com.thinker.mvvm.util
 * 时间：2018/12/28 14:11
 * 描述：SharedPreferences 工具集合
 */
var SP_FILE_NAME = "defaultName"

fun Context.getSp(): SharedPreferences {
    return getSharedPreferences(SP_FILE_NAME, Context.MODE_PRIVATE)
}

/**
 * 数据保存再sp，只支持sp支持的基本类型
 */
fun Context.spSet(keyName: String?, keyValue: Any?) {
    if (keyName == null || keyValue == null) {
        return
    }
    try {
        getEditor(keyName, keyValue).apply()
    } catch (e: Throwable) {
        e.printStackTrace()
    }
}

fun Context.spCommit(keyName: String?, keyValue: Any?): Boolean {
    if (keyName == null || keyValue == null) {
        return false
    }
    return try {
        getEditor(keyName, keyValue).commit()
    } catch (e: Throwable) {
        e.printStackTrace()
        false
    }
}

fun Context.spRemove(keyName: String) {
    getSp().edit().remove(keyName).apply()
}

private fun Context.getEditor(keyName: String?, keyValue: Any?) = getSp().edit().apply {
    when (keyValue) {
        is String -> {
            putString(keyName, keyValue)
        }
        is Boolean -> {
            putBoolean(keyName, keyValue)
        }
        is Int -> {
            putInt(keyName, keyValue)
        }
        is Float -> {
            putFloat(keyName, keyValue)
        }
        is Set<*> -> {
            putStringSet(keyName, keyValue as Set<String>)
        }
        is Long -> {
            putLong(keyName, keyValue)
        }
        else -> {
            putString(keyName, gson.toJson(keyValue))
        }
    }
}

/**
 * 从sp获取数据
 */
inline fun <reified T> Context.spGet(keyName: String, default: T): T {
    try {
        val result: Any?
        when (default) {
            is String -> {
                result = getSp().getString(keyName, default)
            }
            is Boolean -> {
                result = getSp().getBoolean(keyName, default)
            }
            is Float -> {
                result = getSp().getFloat(keyName, default)
            }
            is Int -> {
                result = getSp().getInt(keyName, default)
            }
            is Long -> {
                result = getSp().getLong(keyName, default)
            }
            is Set<*> -> {
                result = getSp().getStringSet(keyName, default as Set<String>)
            }
            else -> {
                result = gson.fromJson(getSp().getString(keyName, ""), T::class.java)
            }
        }
        return result as T
    } catch (e: Throwable) {
        return default
    }
}